﻿App.page({
	id: 'logon',
	url: '/page/logon',
	require: ['signalr', 'user', 'alert'],
	init: function () {
		var $cont = $('.page-container'),
			$form = $('#logon-form'),
			$submitButton = $('#submit-button');

		App.ready(function () {
			$(document.body).removeAttr('style');

			if ($cont.css('opacity') == 0) {
				TweenMax.set($cont, { scale: 0.5 });
				TweenMax.set($cont, { scale: 1 });
				TweenMax.to($cont, 0.5, { opacity: 1 });
			}
		});

		$('[data-auth]').click(function (e) {
			e.preventDefault();
			var url = '/login?provider=' + $(this).attr('data-auth');
			var w = 800;
			var h = 600;
			var params = 'width={w}, height={h}, top={t}, left={l}, directories=no, location=no, menubar=no, resizable=no, scrollbars=no, status=no, toolbar=no'
			.replace('{w}', w).replace('{h}', h).replace('{l}', (screen.width - w) / 2).replace('{t}', (screen.height - h) / 2);
			var popup = window.open(url, App.name, params);
			window.focus && popup.focus();
		});

		$form.bind('keyup keypress', function (e) {
			var code = e.keyCode || e.which;
			if (code == 13) {
				e.preventDefault();
				$submitButton.click();
				return false;
			}
			return true;
		}).validate({
			rules: {
				name: {
					required: true,
					minlength: 3,
					maxlength: 15,
					regex: /^[А-яA-z0-9_-]{3,15}$/g
				}
			},
			messages: {
				name: {
					required: Localization.NameValidationRequired,
					minlength: Localization.NameValidationMinLength,
					maxlength: Localization.NameValidationMaxLength,
					regex: Localization.NameValidationRegex
				}
			},
			showErrors: function (map, list) {
				TweenMax.killTweensOf($submitButton);

				if (!App.isUndefined(map.name)) {
					$submitButton.addClass('uk-button-danger').text(map.name);
					TweenMax.to($submitButton, 1, {
						delay: 3,
						className: '-=uk-button-danger',
						ease: Elastic.easeOut,
						onStart: function () {
							$submitButton.removeClass('uk-button-danger').text('Представиться!');
						}
					});
				}

				this.defaultShowErrors();
			},
			errorPlacement: function (e, el) { return true; },
			errorClass: 'uk-form-danger',
			onsubmit: false,
			onfocusout: false,
			onkeyup: false,
			onclick: false,
			focusCleanup: true
		});

		$submitButton.click(function () {
			if (!$form.valid()) return;

			$('#overlay').show();

			App.signalr.start().done(function () {
				App.signalr.server({
					hub: 'gameHub',
					action: 'initializeUser',
					data: $form.find('input').val()
				}).fail(function (e) {
					App.alert.warning(Localization.ConnectionError);
					console.log('logon.page.js', e);
				}).done(function (r) {
					if (App.isUndefined(r)) return;
					App.user.init(r);
					App.goToPage('intro');
				});
			});
		});
	}
});